<?php
/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class Controller extends CController
{
	/**
	 * @var string the default layout for the controller view. Defaults to '//layouts/column1',
	 * meaning using a single column layout. See 'protected/views/layouts/column1.php'.
	 */
	public $layout='//layouts/column1';
	/**
	 * @var array context menu items. This property will be assigned to {@link CMenu::items}.
	 */
	public $menu = array();
	public $submenu = array();
	/**
	 * @var array the breadcrumbs of the current page. The value of this property will
	 * be assigned to {@link CBreadcrumbs::links}. Please refer to {@link CBreadcrumbs::links}
	 * for more details on how to specify this property.
	 */
	public $breadcrumbs = array();

	public $result_ids = array();
	protected $_result = array();

	public $activeMenu;

	public $defaultAction = 'manage';

	protected $_perms_map = null;

	public function __construct($id, $module = null) {
		if ( getQuery('pageSize') > 0 ) {
			Yii::app()->user->setState('pageSize', getQuery('pageSize'));
			unset($_GET['pageSize']);
		}

		parent::__construct($id, $module);
	}

	public function filters()
    {
        return array(
            'accessControl',
			'permission',
        );
    }

    public function accessRules()
    {
        return array(
            array('allow',
                'users'=>array('*'),
                'actions'=>array('login', 'captcha'),
            ),
            array('allow',
                'users'=>array('@'),
            ),
            array('deny',
                'users'=>array('*'),
            ),
        );
    }

	public function filterPermission($filterChain) {
		if ( app()->user->id == 1 ) {
			$filterChain->run();
			return true; // root admin => full access
		}

		$controller = $filterChain->controller->getId();
		$action = $filterChain->action->getId();

		if ( $controller == 'dashboard' && $action == 'manage' ) {
			if ( !app()->user->isAdmin() ) {
				//$this->accessDenied();
				$this->redirect(param('frontUrl'));
				return true;
			}
		}

		if ( ( $controller == 'site' && ($action == 'manage' || $action == 'error' || $action == 'logout' || $action == 'login' || $action == 'captcha') )
			|| ( $controller == 'dashboard' && $action == 'manage' )
			) {
			$filterChain->run();
			return true;
		}

		$hash = sprintf("%s_%s", $controller, $action);
		$perm = false;
		if ( $this->_perms_map === null ) {
			$this->_perms_map = array(
				'user' => array(
					'actions' => array(
						'add'					=> 'user_edit',
						'update'				=> 'user_edit',

						'manageGroup'			=> 'usergroup_manage',
						'addGroup'				=> 'usergroup_edit',
						'updateGroup'			=> 'usergroup_edit',
						'deleteGroup'			=> 'usergroup_delete',
						'updateGroupStatus'		=> 'usergroup_manage',

						'getUser'				=> 'product_edit',

					),
					'permission'			=> 'user_manage',
				), 
				
				'site' => array(
					'actions' => array(
						'systemlog'					=> 'systemlog', 
					),
					'permission'			=> 'systemlog',
				)
			);
		}

		if ( isset($this->_perms_map[$controller]) ) {
			if ( isset($this->_perms_map[$controller]['actions'][$action]) ) {
				$perm = $this->_perms_map[$controller]['actions'][$action];
			} elseif ( isset($this->_perms_map[$controller]['permission']) ) {
				$perm = $this->_perms_map[$controller]['permission'];
			}

			if (is_array($perm) ) {
				$request_method = $_SERVER['REQUEST_METHOD'];
				if ( isset($perm[$request_method])) {
					$perm = $perm[$request_method];
				} else {
					$perm = false;
				}
			}
		}

		if ( empty($perm) ) $perm = $hash;

		if ( !app()->user->checkPerm($perm) ) {
			$this->accessDenied();
			return true;
		}

		$filterChain->run();
		return true;
	}

	protected function accessDenied($message = null)
	{
		if ( $message === null ) $message = t('Access Denied');
		$user = app()->user;

		if($user->getIsGuest())
			$user->loginRequired();
		else
			throw new CHttpException(403,$message);
	}

	public function init() {
		$this->result_ids = getParam('result_ids') ? explode(',', getParam('result_ids')) : array();

		$this->activeMenu = $this->getUniqueId();
	}

	public function beforeAction($action)
	{
		if(parent::beforeAction($action))
		{
			// generate menus
			$menu = array();
			$submenu = array();

			$menu[] = array('label' =>'&nbsp;', 'url' => array('/dashboard/manage'), 'itemOptions' => array('id' => 'tabs_home', 'class' => (strpos($this->activeMenu, 'site') === 0 ? 'cm-active' : '')));
			$user = app()->user;
 
			if ( $user->checkPerm('user_manage') || $user->checkPerm('usergroup_manage') || $user->checkPerm('badge_manage') ) {
				$menu[] = array('label' => t('Users'), 'url' => array('/user/manage'), 'itemOptions' => array('id' => 'tabs_users', 'class' => ''), 'linkOptions' => array('onclick' => "return fn_switch_tab('user')"));
				if ( $user->checkPerm('user_manage') ) {
					$submenu['user'][] = array('label' => t('Member'), 'url' => array('/user/manage', 'user_type' => 'C'));
					$submenu['user'][] = array('label' => t('Administrators'), 'url' => array('/user/manage', 'user_type' => 'A'));
				}
				if ( $user->checkPerm('usergroup_manage') ) {
					$submenu['user'][] = array('label' => t('User Groups'), 'url' => array('/user/manageGroup'));
				}
			}
			if ( $user->checkPerm('systemlog') ) {
				$menu[] = array('label' => t('Log'), 'url' => array('/site/systemlog'), 'itemOptions' => array('id' => 'tabs_systemlog', 'class' => ''), 'linkOptions' => array('onclick' => "return fn_switch_tab('site')"));
				
				$submenu['site'][] = array('label' => t('System Log'), 'url' => array('/site/systemlog'));
			}

			$this->menu = $menu;
			$this->submenu = $submenu;

			return true;
		}
		else
			return false;
	}

	public function getOutput($view, $data) {
		return $this->renderPartial($view, $data, true);
	}

	public function renderAjax($view, $data = array()) {
		$html = $this->getOutPut($view, $data);

		$this->ajaxResponse($html);
	}

	public function ajaxResponse($html) {
		$text = $html;

		if ( !empty($this->result_ids) ) {
			foreach ($this->result_ids as $r_id) {
				if (strpos($text, ' id="' . $r_id . '">') !== false) {
					$start = strpos($text, ' id="'.$r_id.'">') + strlen(' id="' . $r_id . '">');
					$end = strpos($text, '<!--' . $r_id . '--></');
					$this->assignHtml($r_id, substr($text, $start, $end - $start));
				// Assume that all data should be put to div with this ID
				}
			}
			$text = '';
		}

		session_write_close();

		$notifications = user()->getNotifications();
		$this->assignVar('notifications', $notifications);

		$response = CJSON::encode(array(
			'text' => trim($text),
			'data' => $this->_result,
		));

		echo $response;

		app()->end();
	}

	public function assignHtml($r_id, $text) {
		$this->_result['html'][$r_id] = $text;
	}

	public function assignVar($var, $value) {
		$this->_result[$var] = $value;
	}

	public function setActiveMenu($menu) {
		$this->activeMenu = $menu;
	}
}